package com.zkh360.service.message.controller.base;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.zkh360.service.message.constant.Constants;
import com.zkh360.service.message.model.Pager;

import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

import java.io.IOException;

/**
 * Created by chuanxi.zhao on 18-1-22.
 */
public class BaseController {

	/**
	 *
	 *
	 * @param response
	 * @param obj
	 * @throws IOException
	 */
	protected void writeJSON(HttpServletResponse response, Object obj) throws IOException {
		response.setContentType("application/json;charset=utf-8");
		response.getWriter().write(JSON.toJSONString(obj, SerializerFeature.WriteMapNullValue));
	}

	/**
	 * 
	 * 
	 * @param currentPage 当前页
	 * @param totalCount  当前页数据个数
	 * @param pager       分页信息
	 */
	public void setPager(Integer currentPage, int totalCount, Pager pager) {
		// 判断是否下一页
		if ((currentPage + 1) * Constants.PAGE_SIZE > totalCount) {
			pager.setNextPage(currentPage + 1);
		} else {
			pager.setNextPage(null);
		}
		// 判断是否上一页
		if (currentPage >= 2) {
			pager.setLastPage(currentPage - 2);
		}

		// 当前页数量
		pager.setTotalCount(totalCount);
	}

	public String getUserName() {
		// 获取当前用户登录名等信息
		UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		return userDetails.getUsername();
	}
}
